package org.swan;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Properties;


public class PrinterSettingFrame extends JDialog {
    DefaultComboBoxModel<PrintService> listModel = new DefaultComboBoxModel<>();
    JTextFieldWithPlaceHolder txtName = new JTextFieldWithPlaceHolder("Your name to identify your computer.");
    JTextFieldWithPlaceHolder txtUpload = new JTextFieldWithPlaceHolder("The URL for upload the information,it likes http://[service]:[port]");
    JTextFieldWithPlaceHolder txtJob = new JTextFieldWithPlaceHolder("The URL for upload the information,it likes http://[service]:[port]");
    JTextPane textPane = new JTextPane();

    protected PrinterSettingFrame() {
        setTitle("Printer Settings");
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("printer.png")));
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        MutableGridLayout layout = new MutableGridLayout(2, 7, 5, 5);
        layout.setWidth(0, 100);
        layout.setHeight(0, 40);
        layout.setHeight(1, 40);
        layout.setHeight(2, 40);
        layout.setHeight(3, 40);
        layout.setHeight(4, 40);
        layout.setHeight(5, .9);
        layout.setHeight(6, 40);
        layout.merge(0, 4, 1, 4);
        layout.merge(0, 5, 1, 5);
        layout.merge(0, 6, 1, 6);
        layout.getBox(0, 6).split(2, 1);
        JPanel panel = new JPanel(layout);
        panel.setLayout(layout);
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : printServices) {
            listModel.addElement(printService);
        }
        panel.add(new JLabel("Your ID:"));
        panel.add(txtName);
        panel.add(new JLabel("Printer:"));
        JComboBox<PrintService> printers = getPrintServiceJComboBox();
        panel.add(printers);
        panel.add(new JLabel("Registered URL:"));
        panel.add(txtUpload);
        panel.add(new JLabel("Job URL:"));
        panel.add(txtJob);
        panel.add(new JLabel("Logging"));
        panel.add(new JScrollPane(textPane));
        panel.add(new JButton(new AbstractAction("Save") {
            @Override
            public void actionPerformed(ActionEvent e) {
                exit(true);
            }
        }));
        panel.add(new JButton(new AbstractAction("Close") {
            @Override
            public void actionPerformed(ActionEvent e) {
                exit(false);
            }
        }));
        getContentPane().add(panel);
        setSize(new Dimension(800, 600));
        setVisible(true);
    }

    public static PrinterSettingFrame show(Properties p) {
        PrinterSettingFrame frame = new PrinterSettingFrame();
        frame.txtName.setText(p.getProperty("name"));
        frame.txtUpload.setText(p.getProperty("register"));
        frame.txtJob.setText(p.getProperty("job"));
        for (int i = 0; i < frame.listModel.getSize(); i++) {
            if (frame.listModel.getElementAt(i).getName().equals(p.getProperty("printer"))) {
                frame.listModel.setSelectedItem(frame.listModel.getElementAt(i));
            }
        }
        return frame;
    }

    private void exit(boolean save) {
        if (save) {
            Properties p = new Properties();
            p.put("name", txtName.getText());
            p.put("register", txtUpload.getText());
            p.put("job", txtJob.getText());
            p.put("printer", ((PrintService) listModel.getSelectedItem()).getName());
            try {
                p.store(Files.newBufferedWriter(Paths.get("config.properties")), "update " + new Date());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        dispose();
    }

    private JComboBox<PrintService> getPrintServiceJComboBox() {
        JComboBox<PrintService> printers = new JComboBox<>(listModel);
        printers.setFont(new Font("Serif", Font.PLAIN, 16));
        printers.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof PrintService) {
                    return super.getListCellRendererComponent(list, ((PrintService) value).getName(), index, isSelected, cellHasFocus);
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        return printers;
    }

    public static void main(String[] args) throws IOException {
        Font font = new Font("Serif", Font.PLAIN, 16);
        UIManager.put("Component.font", font);
        UIManager.put("Label.font", font);
        UIManager.put("TextField.font", font);
        Properties p = new Properties();
        if (Files.exists(Paths.get("config.properties"))) {
            p.load(new FileReader("config.properties"));
        }
        PrinterSettingFrame.show(p);
    }
}
